<?php

require_once('./db/pdo.php');

function updateUser($data, $id, $dbh)
{
    try 
    {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);      
        $dbh->beginTransaction();
        $stmt = $dbh->prepare("UPDATE users SET email = ?, phone = ?, name = ?, username = ?, website = ?, image = ? WHERE id = ?");
        $stmt->bindParam(1, $data['email']);
        $stmt->bindParam(2, $data['phone']);
        $stmt->bindParam(3, $data['name']);
        $stmt->bindParam(4, $data['username']);
        $stmt->bindParam(5, $data['website']);
        $stmt->bindParam(6, $data['image']);
        $stmt->bindParam(7, $id);
        $stmt->execute();
        $dbh->commit();      
    } 
    catch (Exception $e) 
    {
        $dbh->rollBack();
        echo "Ошибка: " . $e->getMessage();
    }
}

function createUser($data, $dbh)
{
    try 
    {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);      
        $dbh->beginTransaction();
        $stmt = $dbh->prepare("INSERT INTO users (email, phone, name, username, website) VALUES (?, ?, ?, ?, ?)");
        $stmt->bindParam(1, $data['email']);
        $stmt->bindParam(2, $data['phone']);
        $stmt->bindParam(3, $data['name']);
        $stmt->bindParam(4, $data['username']);
        $stmt->bindParam(5, $data['website']);
        $stmt->execute();
        $dbh->commit();      
    } 
    catch (Exception $e) 
    {
        $dbh->rollBack();
        echo "Ошибка: " . $e->getMessage();
    }
}

function deleteUser($id, $dbh)
{
    try 
    {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);      
        $dbh->beginTransaction();
        $stmt = $dbh->prepare("DELETE FROM users where id = ?");
        $stmt->execute([$id]);
        $dbh->commit(); 
    }
    catch (Exception $e) 
    {
        $dbh->rollBack();
        echo "Ошибка: " . $e->getMessage();
    }
}

function getUserById($id, $dbh)
{
    $stmt = $dbh->prepare("SELECT * FROM users where id = ?");
    $stmt->execute([$id]);
    return $stmt;
}

function getUsers($dbh)
{
    $stmt = $dbh->prepare("SELECT * from users");
    $stmt->execute();

    return $stmt;
}

function uploadImage($file, $userId) 
{
    if (!is_dir(__DIR__ . '/images'))
    {
        mkdir(__DIR__ . '/images');
    }

    $fileName = $file['name'];

    $path_parts = pathinfo($fileName);
    $extension = $path_parts['extension'];

    echo $path_parts['filename'] . 'userId' . $userId;
    move_uploaded_file($_FILES['picture']['tmp_name'], "./users/images/" . $path_parts['filename'] . 'userId' . $userId . '.' . $extension);
    return "./users/images/" . $path_parts['filename'] . 'userId' . $userId . '.' . $extension;
}